/**
 * www.easyplatform.cn ©2016
 */
package cn.easyplatform.studio.cfg.jta;

import cn.easyplatform.studio.StudioException;
import cn.easyplatform.studio.cfg.TransactionContext;

import javax.transaction.Status;
import javax.transaction.SystemException;
import javax.transaction.Transaction;
import javax.transaction.TransactionManager;

/**
 * @author <a href="mailto:shiny_vc@163.com">陈云亮</a> <br/>
 * @since 2.0.0 <br/>
 */
public class JtaTransactionContext implements TransactionContext {

	protected final TransactionManager transactionManager;

	public JtaTransactionContext(TransactionManager transactionManager) {
		this.transactionManager = transactionManager;
	}

	public void commit() {
	}

	public void rollback() {
		try {
			Transaction transaction = getTransaction();
			int status = transaction.getStatus();
			if (status != Status.STATUS_NO_TRANSACTION
					&& status != Status.STATUS_ROLLEDBACK) {
				transaction.setRollbackOnly();
			}
		} catch (IllegalStateException e) {
			throw new StudioException(
					"Unexpected IllegalStateException while marking transaction rollback only");
		} catch (SystemException e) {
			throw new StudioException(
					"SystemException while marking transaction rollback only");
		}
	}

	@Override
	public void close() {

	}

	protected Transaction getTransaction() {
		try {
			return transactionManager.getTransaction();
		} catch (SystemException e) {
			throw new StudioException(
					"SystemException while getting transaction ", e);
		}
	}
}
